#!/usr/bin/perl -w
use strict;

use FindBin;
use lib ("$FindBin::Bin/..", "/net/cpp-group/Leo/bin");
use db_parameters;
use ensembl_parameters;
use chromosomes;

use DBI;


print STDERR <<"HEADLINE";
888888888888888888888888888888888888888888888888888888888888888888888

    custom

	Description:
		Fill ens_id, prot_exon, gene_loci from passing non-ensembl directories

888888888888888888888888888888888888888888888888888888888888888888888

HEADLINE


#
#	connect to panda
#
my $dbh = connect_to_panda();
use get_psql_time;
my $start_time = get_psql_time($dbh);


#
#	get ensembl taxa
#
my %ensembl_taxa;
for my $ens_data(get_ensembl_taxon_data())
{
	++$ensembl_taxa{$ens_data->[TAXON]};
}

#
#	get custom
#
my %taxon_data = get_taxon_data;
for my $taxon(keys %taxon_data)
{
	next if exists $ensembl_taxa{$taxon};

	print STDERR "\n\tProcessing non-Ensembl species $taxon...\n";
	my $sequence_dir = $taxon_data{$taxon}[SEQ_DIR];


	my %prot_id_to_gene_id;
	#
	#	ens_id
	#
	{
		# clear up previous data
		$dbh->do("DELETE FROM public.ens_id where species = '$taxon';");

		# open file
		print STDERR "\tCopying IDs to table.ens_id\n";
		my $ens_id_file = "$sequence_dir/prot_id_to_gene_id.map";
		die "Error:\n\t$ens_id_file does not exist\n" unless (-f "$ens_id_file");
		open ENS_ID, $ens_id_file or die;

		# copy to panda
		$dbh->do("COPY public.ens_id(species, gene_id, prot_id,  transcript_id) FROM STDIN");
		my $cnt_line = 0;
		while (<ENS_ID>)
		{
			++$cnt_line;
			$dbh->pg_putline($_);
			my (undef, $gene_id, $prot_id, undef) = split /\t/;
			$prot_id_to_gene_id{$prot_id} = $gene_id;
		}
		$dbh->pg_putline("\\.\n");
		$dbh->pg_endcopy;
		$dbh->do("VACUUM ANALYSE public.ens_id;");

		print STDERR "\t$cnt_line identifiers placed in public.ens_id\n";

	}
}

print STDERR "\tCompleted\n";

log_pipeline_stage($dbh, 'NULL', 20, 'table ens_id', $start_time);
$dbh->disconnect();

